 
layui.use('layer', function(){
    var layer = layui.layer;
});
navigator.getUserMedia  = navigator.getUserMedia || 
                          navigator.webkitGetUserMedia ||
                          navigator.mozGetUserMedia || 
                          navigator.msGetUserMedia
var localVideo = document.getElementById("localVideo");
var remoteVideo = document.getElementById("remoteVideo");
//枚举，代表三个页面
var Pages = {
    //登录页面
    login: 0,
    //联系人
    contacts: 1,
    //私聊界面
    privateChat: 2,
    //群聊界面
    groupChat: 3
}; 
//标记所处的页面和当前聊天的好友
var currentPage = {
    page: Pages.login,
    currentUser: null,
    currentChatFriend: null,
    currentChatGroup: null
};

//为了避免controller层侵入到service层，用controller层的代码覆盖service层的预置方法
// chatService.onNewPrivateMessageReceive = onNewPrivateMessageReceive;
// chatService.onPrivateHistoryLoad = onPrivateHistoryLoad;
// chatService.onNewGroupMessageReceive = onNewGroupMessageReceive;
// chatService.onGroupHistoryLoad = onGroupHistoryLoad;
// chatService.onFriendListChange = onFriendListChange;
// chatService.onGroupListChange = onGroupListChange;

//登录
function login() {
    var username = $("#username").val();
    var password = $("#password").val();
    var resultStatus = chatService.login(username, password);
    if (resultStatus) {
        //初始化GoEasy和本地好友列表 
        $("#login-box").hide();
        //切换到联系人
        switchToContacts();
    } else {
        //显示错误信息
        $("#login-error-box").show();
    }
}

//切换到联系人界面
function switchToContacts() {
    //设置当前页面为好友列表页面
    var dataArr = JSON.parse(sessionStorage.getItem('loginData'));
    $("#login-box").hide();
    currentPage.page = Pages.contacts;
    //修改页面的title
    $("title").text("联系人");
    $('.login').hide() 
    //初始化当前用户
    // currentPage.currentUser = dataArr.currentUser;
    $("#current-user-avatar").attr("src", 'images/Avatar-'+parseInt(Math.random()*5)+".png");
    $("#current-user-name").text(dataArr.username);

    //隐藏聊天窗口
    $("#chat-box").hide();   
    //绘制好友列表
    renderFriendList(dataArr.allFriend);
    //显示好友列表
    $("#friends-box").show();
 
}

//绘制好友列表
function renderFriendList(friends) { 
    var friendListDiv = $("#friend-list");
    friendListDiv.empty();
    for (var key in friends) { 
        var item = $("#friend-item-template").clone();//好友信息的模版
        item.remove('#friend-item-template');
        var friend = friends[key];

        //更新好友uuid
        item.attr("id", friend.to_uuid);
        // item.children(".friend-item-message-badge").children(".message-count").html(friend.msgCount);
        //设置好友头像
        var friendAvatarImg = item.find("img");
        friendAvatarImg.attr("src", 'images/Avatar-'+parseInt(Math.random()*5)+".png");
        friendAvatarImg.attr("id", "avatar_" + key);
        //设置好友名称
        item.find(".friend-name").html(friend.toMember);
        //更新未读消息数
        // var unReadMessage = friend.unReadMessage;
        item.find(".message-count").text(friend.msgCount);

        // 显示或隐藏未读消息数
        var messageBadge = item.find(".friend-item-message-badge");
        if (friend.msgCount == 0) {
            //没有未读消息，隐藏消息数量
            messageBadge.hide();
        } else {
            //有未读消息，展现未读消息量
            messageBadge.show();
        }

        //添加点击事件，点击好友条目后，进入聊天窗口
        (function (key) {
            var friend = friends[key]
            item.click(function () { 
                var dataArr = getLoginData(); 
                dataArr.allFriend[key].msgCount = 0;
                sessionStorage.setItem('loginData',JSON.stringify(dataArr)); 
                item.children(".friend-item-message-badge").children(".message-count").html(0); 
                sessionStorage.setItem('currentFriendImg',item.find("img").attr("src"));
                switchToPrivateChat(friend);
            });
        })(key)

        //将一条好友添加到好友的列表中
        friendListDiv.append(item);

        if (friend.online) {
            $("#avatar_" + key).removeClass("friend-avatar-desaturate");
        }
    }
}

 

//切换到私聊界面
function switchToPrivateChat(friend) {
    var userData = getLoginData(); 
    send({"act":"getChatLog","to_uuid":friend.to_uuid,"uuid_to":userData.uuid});
    //设置当前页面为聊天页面和聊天的好友
    currentPage.page = Pages.privateChat;
    currentPage.currentChatFriend = friend;
    $("title").text("私聊界面");

    //先清空之前的聊天内容
    var chatBoxContent = $("#chat-box-content");
    chatBoxContent.empty();

    //隐藏好友列表
    $("#friends-box").hide();
    //更新当前聊天的好友名称
    $(".current-friend-name").text(friend.toMember);

    //显示聊天窗口
    $("#chat-box").show();

    $("#sendMessageButton").off('click').on("click", function () {
        sendPrivateChatMessage(friend.to_uuid);
    });
    
    $("#faceToChat").off('click').on("click", function () {  
        // sessionStorage.setItem('to_uuid',friend.to_uuid);
        sessionStorage.setItem('callTo',true); 
        send({"act":"faceToChat","to_uuid":friend.to_uuid,"uuid_to":userData.uuid});
    });

    //绘制聊天消息
 
        renderPrivateChatMessage(friend.to_uuid,true) 
}
 

//私聊回到联系人
function privateChatBackToContacts() {
    // chatService.resetFriendUnReadMessage(currentPage.currentChatFriend);
    switchToContacts()
}
var myImage =  'images/Avatar-'+parseInt(Math.random()*5)+".png";
// 发送私聊消息
function sendPrivateChatMessage() {
    //获取content并赋值
    var messageInputBox = $("#send-input-box");
    var currLoginUser = JSON.parse(sessionStorage.getItem('loginData'));
    var content = messageInputBox.val();
    if (content != '' && content.trim().length > 0) {
        var chatBoxContent = $("#chat-box-content"); 
        // chatBoxContent.empty(); 
            var messageTemplate; 
                //自己发送的消息展示在右边
            messageTemplate = $("#chat-box-self-message-template").clone();
            messageTemplate.remove('#chat-box-self-message-template');
            //更新头像
            messageTemplate.find("img").attr("src", myImage);
            
            messageTemplate.find(".chat-message").text(content);
            //显示一条消息到页面上
            chatBoxContent.append(messageTemplate); 
        // 发送消息
        send({'act':'chatLine','uuid_to':currLoginUser.uuid,'to_uuid':currentPage.currentChatFriend.to_uuid,'content':content,'memberTo':currLoginUser.username});
        // chatService.sendPrivateMessage(currentPage.currentChatFriend.uuid, content);
        //发送消息后输入框清空
        messageInputBox.val("");
    }
}


//监听私聊消息加载
function onPrivateHistoryLoad(friendId, messages) {
    if (messages.length == 0) {
        $('#top').html('已经没有更多的历史消息');
        $('#top').css({color: 'gray', textDecoration: 'none'});
        return
    }
    var chatMessages = chatService.getPrivateMessages(friendId)
    renderPrivateChatMessage(chatMessages)
}

//绘制界面私聊消息
function renderPrivateChatMessage(privateMessages, scrollToBottom=true) {
    var chatBoxContent = $("#chat-box-content");
    var currLoginUser = JSON.parse(sessionStorage.getItem('loginData'));
    // chatBoxContent.empty();
    $.each(privateMessages,function (index,message) {
        var messageTemplate;
        //判断这条消息是谁发的
        if (message.to_uuid != currLoginUser.uuid) {
            //自己发送的消息展示在右边
            messageTemplate = $("#chat-box-self-message-template").clone();
            messageTemplate.remove('#chat-box-self-message-template');
            //更新头像
            messageTemplate.find("img").attr("src", myImage);
        } else {
            //如果该为好友发送的消息展示在左边
            messageTemplate = $("#chat-box-friend-message-template").clone();
            messageTemplate.find("img").attr("src", sessionStorage.getItem('currentFriendImg'));
        }
        messageTemplate.find(".chat-message").text(message.content);
        //显示一条消息到页面上
        chatBoxContent.append(messageTemplate);
    });

    //将滚动条拉到最下
    scrollToBottom && $('#private-box').scrollTop($('#private-box')[0].scrollHeight);
}
 
//监听接收私聊消息
function onNewPrivateMessageReceive(friendId, chatMessage) {
    // let friend = chatService.friends[friendId];
    //如果当前窗口是在好友列表页面，只显示未读消息数
    if (currentPage.page == Pages.contacts) { 
        var friendUUid = friendId[0].uuid_to
        var messageBadge = $("#"+friendUUid).find(".friend-item-message-badge");
   
        messageBadge.show(); 
        var msgCount = parseInt($("#"+friendUUid).children(".friend-item-message-badge").children(".message-count").html()); 
        $("#"+friendUUid).children(".friend-item-message-badge").children(".message-count").html(msgCount+1);
        
    } else {
        // if (friendId == currentPage.currentChatFriend.to_uuid) {
            renderPrivateChatMessage(friendId, true)
        // }
    }
}
 
//更新好友列表
function onFriendListChange(friends) {
    renderFriendList(friends)
}

 

    var wsServer = 'wss://swoole.mveris.cn:9501';
    var webSocket = new WebSocket(wsServer);;


    webSocket.onopen = function (evt) {
        console.log("Connected to WebSocket server.");
    };

    webSocket.onclose = function (evt) {
        console.log("Disconnected");
    };

    webSocket.onmessage = function (evt) {
        var dataArr = JSON.parse(evt.data);
     
        if(dataArr.status == 1){
            switch(dataArr['act']){
            case 'open': 
                break;
            case 'userLogin':  
                sessionStorage.setItem('loginData',JSON.stringify(dataArr['data']));
                $("#login-box").hide();
                currentPage.page = Pages.contacts;
                //修改页面的title
                $("title").text("联系人");
                $('.login').hide() 
                //初始化当前用户
                // currentPage.currentUser = dataArr.currentUser;
                $("#current-user-avatar").attr("src", 'images/Avatar-'+parseInt(Math.random()*5)+".png");
                $("#current-user-name").text(dataArr.username);
            
                //隐藏聊天窗口
                $("#chat-box").hide();  
             
                //绘制好友列表
                renderFriendList(dataArr.data.allFriend);
                //显示好友列表
                $("#friends-box").show();
            break;

            case 'userRegister':
                layer.msg(dataArr.msg);
            break;
            case 'confirmAdd':
                layer.msg(dataArr.msg);
            break;
            case 'searchContacts':
                var item = $("#friend-item-template").clone();
                item.remove('#friend-item-template').css("margin-top",0);
                item.children(".friend-item-box").children(".friend-name").html(dataArr.data.username);
                item.children(".friend-item-message-badge").css("margin","0 20px auto auto").empty().append("<button onClick='sureInsert(\""+dataArr.data.uuid+"\")' class='layui-btn layui-btn-radius layui-btn-normal'  >添加</button>");
                // .attr('data-value',dataArr.data.uuid);
                // item.children(".friend-item-message-badge").children(".message-count").html('添加好友');
                $(".appendSearch").empty().append(item);
               
            break;
            case 'NewApply':
                layer.msg(dataArr.msg);
            break;
            case 'completeRecord':
                $(".appendSearch").empty();
                $.each(dataArr.data,function(index,val){
                    var item = $("#friend-apply-template").clone(); 
                    item.css("margin-top",0).attr('id', val._id.$oid);
                    item.children(".friend-item-box").children(".friend-name").html(val.memberTo);
                    item.children(".friend-apply-badge").css("margin","0 20px auto auto").children("button").attr("data-value",val._id.$oid);
                    $(".completeRecord").append(item);
                })
                var index = layer.open({
                    offset: 'auto',
                    title:'申请记录',
                    type: 1, 
                    content: $(".completeRecord"), //这里content是一个普通的String
                    cancel: function(index, layero){ 
                        if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                            $(".completeRecord").empty();
                            layer.close(index)
                        }
                        return false; 
                      } 
                });
                layer.full(index);
               
                // var item = $("#friend-item-template").clone();
                // item.remove('#friend-item-template').css("margin-top",0);
                // item.children(".friend-item-box").children(".friend-name").html(dataArr.data.username);
                // item.children(".friend-item-message-badge").css("margin","0 20px auto auto").empty().append("<button onClick='sureInsert(\""+dataArr.data.uuid+"\")' class='layui-btn layui-btn-radius layui-btn-normal'  >添加</button>");
                //  $(".appendSearch").empty().append(item);
            break;
            case 'Auditors':
                var userLoginData = getLoginData(); 
                userLoginData['allFriend'].push(dataArr['friendData']); 
                sessionStorage.setItem('loginData',JSON.stringify(userLoginData));
                console.log(getLoginData());
                renderFriendList(getLoginData().allFriend);
                $("#"+dataArr.friendData._id.$oid).remove();
            case 'ToPushAuditors':
                var userLoginData = getLoginData();
                userLoginData.allFriend.push(dataArr['data']);
                renderFriendList(userLoginData['allFriend']);
                sessionStorage.setItem('loginData',JSON.stringify(userLoginData));
            break;
            case 'getChatLog':
                onNewPrivateMessageReceive(dataArr.data);
            break;
            case 'getMsg':
                onNewPrivateMessageReceive(dataArr.data);
            break;
            case 'getFaceToCall':  
                sessionStorage.setItem('uuid_to',dataArr.data.uuid_to);
                var index = layer.open({
                    id: 'faceToChatPage',
                    offset: 'auto',
                    title:'视频聊天',
                    type: 2, 
                    content: 'faceTochat.html',
                    cancel: function(index, layero){ 
                        if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                            sessionStorage.removeItem('callTo')
                            layer.close(index)
                        }
                        return false; 
                    },
                    success: function(layero, index){
                        console.log('getFaceToCall');
                    }
                    
                })     
                layer.full(index); 
            break;
            case 'faceToChat':
                var index = layer.open({
                    id: 'faceToChatPage',
                    offset: 'auto',
                    title:'视频聊天',
                    type: 2, 
                    content: 'faceTochat.html',
                    cancel: function(index, layero){ 
                        if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                            sessionStorage.removeItem('callTo')
                            layer.close(index)
                        }
                        return false; 
                    },
                    success: function(layero, index){
               
                    }
                    
                })    
                layer.full(index);  
        
            break;
            case 'loginOut':
                layer.msg(dataArr.msg);
                setTimeout(function() {
                    sessionStorage.clear();
                    window.location.reload();
                }, 2000);
                
            break;
        }
        }else{
            layer.msg(dataArr.msg);
        }
    
        
    };

    webSocket.onerror = function (evt, e) {
        console.log('Error occured: ' + e);
    };

    function send(data){ 
        webSocket.send(JSON.stringify(data));
    } 

    function userLogin()
    { 
        this.send({"act":"userLogin","username":$("#username").val(),"passwd":$("#password").val()});
    }
    function register()
    { 
        this.send({"act":"userRegister","username":$("#registerUser").val(),"passwd":$("#registerPasswd").val()});
    }
    function toRegister(){
        $(".register").show();
        $(".login").hide();
    }
    function toLogin(){
        $(".login").show();
        $(".register").hide();
    }
    function toSearch(){
        $(".searchContans").show();
  
        var index = layer.open({
            offset: 'auto',
            title:'搜索联系人',
            type: 1, 
            content: $(".searchContans"), //这里content是一个普通的String
            cancel: function(index, layero){ 
                if(confirm('确定要关闭么')){ //只有当点击confirm框的确定时，该层才会关闭
                    $(".appendSearch").empty();
                    layer.close(index)
                }
                return false; 
              } 
        });
        layer.full(index);
    }
    function getLoginData(){
        return JSON.parse(sessionStorage.getItem('loginData'));
    }
    function searchContacts(){
        var searchPeopleName = $("#searchPeopleName").val();
        var loginData = getLoginData();
        this.send({"act":"searchContacts","toUsername":searchPeopleName,"usernameTo":loginData.username});
    }
    function sureInsert(toMember){
        var loginData = getLoginData();
        this.send({"act":"confirmAdd","toMember":toMember,"uuid":loginData.uuid,"memberTo":loginData.username});
    }
    function showApply(){
        var loginData = getLoginData();
        this.send({"act":"completeRecord","toMember":loginData.username});
    }
    function Auditors(obj){  
        this.send({"act":"Auditors","object":$(obj),"_id":$(obj).attr('data-value'),"opertion":true});
    }
 


 
 